package com.mx.beautiful.biz;

import java.util.ArrayList;
import java.util.regex.Matcher;

import android.content.Context;

import com.mx.beautiful.constants.Urls;
import com.mx.beautiful.model.GirlType;
import com.mx.beautiful.model.GirlTypeItem;
import com.mx.beautiful.utils.FileUtil;
import com.mx.beautiful.utils.IntentUtil;

public class BeautifulGirlListBiz {
	private final String RegexMainList = "(?<=<DIV\\sclass=pic_mian_jj>[\\s\\S]{0,10})<ul>[\\s\\S]*?</ul>";
	// "[\\s\\S]*?</UL>";

	private final String RegexPageTitle = "(?<=<DIV\\sclass=pic_mian_dao>)[\\s\\S]*?(?=</DIV>)";

	private final String RegexItem = "<Li>[\\s\\S]*?</li>";
	private final String RegexTarget = "(?<=href=\\\")[\\s\\S]*?(?=\\\")";
	private final String RegexTitle = "(?<=title=\\\")[\\s\\S]*?(?=\\\")";
	private final String RegexImage = "(?<=src=\\\")[\\s\\S]*?(?=\\\")";

	private final String RegexPre = "(?<=<a\\s{0,5}class='pre'\\s{0,5}href=')[^']*?(?=')";

	public GirlType getGirlTypeList(String Url, Context context) {
		String htmlCode = IntentUtil.doGet(Url, context);
		if (htmlCode == null)
			return null;
		GirlType girlType = new GirlType();
		/*
		 * title
		 */
		Matcher matcherTitle = FileUtil.getPattern(RegexPageTitle, htmlCode);
		if (matcherTitle.find()) {
			girlType.setTitle(matcherTitle.group());
		}
		/*
		 * list
		 */
		girlType.setList(new ArrayList<GirlTypeItem>());
		Matcher matcher = FileUtil.getPattern(RegexMainList, htmlCode);
		if (!matcher.find())
			return null;
		String strItems = matcher.group();
		Matcher matcherItems = FileUtil.getPattern(RegexItem, strItems);
		while (matcherItems.find()) {
			String strLi = matcherItems.group();
			Matcher mTarget = FileUtil.getPattern(RegexTarget, strLi);
			Matcher mTitle = FileUtil.getPattern(RegexTitle, strLi);
			Matcher mImage = FileUtil.getPattern(RegexImage, strLi);
			mTarget.find();
			mTitle.find();
			mImage.find();
			String strTarget = Urls.PageUrlMain + mTarget.group();
			String strTitle = mTitle.group();
			String strImage = Urls.PageUrlMain + mImage.group();
			GirlTypeItem item = new GirlTypeItem();
			item.setImageUrl(strImage);
			item.setName(strTitle);
			item.setTarget(strTarget);
			girlType.getList().add(item);
		}
		/*
		 * pageCount
		 */
		Matcher mPre = FileUtil.getPattern(RegexPre, htmlCode);
		if (mPre.find()) {
			girlType.setPreviousUrl(Urls.PageUrlMXLZ + mPre.group());
		}
		if (mPre.find()) {
			girlType.setNextUrl(Urls.PageUrlMXLZ + mPre.group());
		}

		return girlType;
	}
}
